package com.example.mq.jms;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class QueueProducer {

    //默认用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKER_URL);
        String queueString = "activemq-queue-test1";
        String text = "测试点对点的一条消息";
        //sendMessageJms10(connectionFactory,queueString,text);
        sendMessageJms20(connectionFactory,queueString,text);

    }

    private static void sendMessageJms10(ConnectionFactory connectionFactory,String queueString,String text){
        try {
            //创建连接
            Connection connection = connectionFactory.createConnection();
            //启动连接
            connection.start();
            try {
                //创建会话
                Session session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
                //创建队列，需要指定队列名称，消息生产者和消费者将根据它来发送、接收对应的消息
                Queue myTestQueue = session.createQueue(queueString);
                //消息生产者
                MessageProducer producer = session.createProducer(myTestQueue);
                //创建一个消息对象
                TextMessage message = session.createTextMessage(text);
                //发送一条消息
                producer.send(message);
                session.commit();
                //关闭资源
                session.close();
                //提交事务
            }finally {
                connection.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("user:"+USERNAME+",password:"+PASSWORD+",broker_url:"+BROKER_URL);
        }
    }

    private static void sendMessageJms20(ConnectionFactory connectionFactory,String queueString,String text){
       /* try {
            JMSContext context = connectionFactory.createContext();
            Queue queue = context.createQueue(queueString);
            context.createProducer().send(queue,text);
        }catch (JMSRuntimeException e){
            e.printStackTrace();
        }*/

    }
}
